<template>
  <div class="order-submit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>确认订单信息</span>
        </div>
      </template>
      
      <!-- 收货地址 -->
      <div class="address-section">
        <div class="section-title">收货地址</div>
        <div v-if="selectedAddress" class="selected-address">
          <div class="address-info">
            <p>
              <span class="receiver">{{ selectedAddress.name }}</span>
              <span class="phone">{{ selectedAddress.phone }}</span>
            </p>
            <p class="address">
              {{ selectedAddress.province }}
              {{ selectedAddress.city }}
              {{ selectedAddress.district }}
              {{ selectedAddress.detailAddress }}
            </p>
          </div>
          <el-button type="primary" link @click="showAddressDialog = true">修改</el-button>
        </div>
        <div v-else class="no-address">
          <el-button type="primary" @click="showAddressDialog = true">添加收货地址</el-button>
        </div>
      </div>

      <!-- 商品信息 -->
      <div v-if="orderData.items && orderData.items.length > 0" class="products-section">
        <div class="section-title">商品信息</div>
        <div v-for="item in orderData.items" :key="item.productId" class="product-item">
          <el-image :src="item.productPic" :alt="item.productName" class="product-img"></el-image>
          <div class="product-info">
            <div class="product-name">{{ item.productName }}</div>
            <div class="product-attr" v-if="item.productAttr">{{ item.productAttr }}</div>
            <div class="product-price">
              <span class="price">¥{{ item.productPrice }}</span>
              <span class="quantity">x {{ item.quantity }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-order">
        <el-empty description="暂无订单数据"></el-empty>
      </div>

      <!-- 订单金额 -->
      <div v-if="orderData.items && orderData.items.length > 0" class="amount-section">
        <div class="amount-item">
          <span>商品总额：</span>
          <span class="price">¥{{ orderData.totalAmount }}</span>
        </div>
        <div class="amount-item">
          <span>运费：</span>
          <span class="price">¥{{ freightAmount }}</span>
        </div>
        <div class="amount-item total">
          <span>应付总额：</span>
          <span class="price">¥{{ totalAmount }}</span>
        </div>
      </div>

      <!-- 提交订单 -->
      <div class="submit-section">
        <el-button 
          type="primary" 
          size="large" 
          @click="submitOrder" 
          :loading="submitting"
          :disabled="!orderData.items || orderData.items.length === 0"
        >
          提交订单
        </el-button>
      </div>
    </el-card>

    <!-- 地址选择弹窗 -->
    <el-dialog
      v-model="showAddressDialog"
      title="选择收货地址"
      width="50%"
    >
      <div class="address-list">
        <div
          v-for="address in addressList"
          :key="address.id"
          class="address-item"
          :class="{ active: selectedAddress?.id === address.id }"
          @click="selectAddress(address)"
        >
          <div class="address-content">
            <p>
              <span class="receiver">{{ address.name }}</span>
              <span class="phone">{{ address.phone }}</span>
            </p>
            <p class="address">
              {{ address.province }}
              {{ address.city }}
              {{ address.district }}
              {{ address.detailAddress }}
            </p>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddressDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmAddress">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createOrder } from '@/api/order'
import { listAddress } from '@/api/member/address'
import { getAuctionDetail } from '@/api/auction'

const router = useRouter()
const route = useRoute()

// 订单数据
const orderData = ref({
  items: [],
  totalAmount: 0
})
const selectedAddress = ref(null)
const addressList = ref([])
const showAddressDialog = ref(false)
const submitting = ref(false)

// 运费和总金额
const freightAmount = ref(0)
const totalAmount = computed(() => {
  return orderData.value.totalAmount + freightAmount.value
})

// 获取收货地址列表
const getAddressList = async () => {
  try {
    const res = await listAddress()
    console.log('地址列表返回数据:', res)
    if (res.code === 200) {
      const addressData = res.rows || res.data || []
      console.log('处理后的地址数:', addressData)
      addressList.value = addressData
      // 默认选择第一个地址
      if (addressList.value.length > 0 && !selectedAddress.value) {
        selectedAddress.value = addressList.value[0]
      } else {
        console.log('没有可用的地址数据')
      }
    } else {
      console.error('获取地址列表失败:', res)
      ElMessage.error(res.msg || '获取收货地址失败')
    }
  } catch (error) {
    console.error('获取收货地址失败:', error)
    ElMessage.error('获取收货地址失败，请稍后重试')
  }
}

// 获取拍卖商品数据
const getAuctionOrderData = async (auctionId) => {
  try {
    const res = await getAuctionDetail(auctionId)
    console.log('拍卖商品数据:', res)
    if (res.code === 200 && res.data) {
      const auctionData = res.data
      orderData.value = {
        totalAmount: auctionData.currentPrice || auctionData.startPrice,
        items: [{
          productId: auctionData.productId,
          productName: auctionData.product?.name,
          productPic: auctionData.product?.pic,
          productPrice: auctionData.currentPrice || auctionData.startPrice,
          quantity: 1
        }]
      }
      console.log('处理后的订单数据:', orderData.value)
    } else {
      ElMessage.warning('获取拍卖商品信息失败')
    }
  } catch (error) {
    console.error('获取拍卖商品数据失败:', error)
    ElMessage.warning('获取拍卖商品信息失败')
  }
}

// 选择收货地址
const selectAddress = (address) => {
  selectedAddress.value = address
}

// 确认地址选择
const confirmAddress = () => {
  showAddressDialog.value = false
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (!orderData.value || !orderData.value.items || !Array.isArray(orderData.value.items) || orderData.value.items.length === 0) {
    ElMessage.warning('订单数据不完整')
    return
  }

  if (submitting.value) return
  submitting.value = true

  try {
    const orderSubmitData = {
      totalAmount: orderData.value.totalAmount,
      payAmount: totalAmount.value,
      freightAmount: freightAmount.value,
      payType: 1, // 支付方式，1为在线支付
      receiverName: selectedAddress.value.name,
      receiverPhone: selectedAddress.value.phone,
      receiverPostCode: selectedAddress.value.postCode,
      receiverProvince: selectedAddress.value.province,
      receiverCity: selectedAddress.value.city,
      receiverDistrict: selectedAddress.value.district,
      receiverDetailAddress: selectedAddress.value.detailAddress,
      note: '', // 订单备注
      items: orderData.value.items.map(item => ({
        productId: item.productId,
        productName: item.productName,
        pic: item.productPic,
        salePrice: item.productPrice,
        quantity: item.quantity
      }))
    }

    // 如果是拍卖商品，添加拍卖相关信息
    if (route.query.fromAuction) {
      orderSubmitData.fromAuction = true
      orderSubmitData.auctionId = route.query.auctionId
    }

    console.log('提交订单数据:', orderSubmitData)
    const res = await createOrder(orderSubmitData)
    console.log('创建订单响应:', res)

    if (res.code === 200 && res.data) {
      // 清除订单数据（仅清除非拍卖订单的数据）
      if (!route.query.fromAuction) {
        sessionStorage.removeItem('orderData')
      }
      
      // 获取订单号
      const orderSn = res.data.orderSn
      if (!orderSn) {
        throw new Error('创建订单失败：未获取到订单号')
      }
      
      console.log('创建订单成功，订单号:', orderSn)
      ElMessage.success('订单创建成功')
      
      // 跳转到支付页面
      router.push(`/order/pay/${orderSn}`)
    } else {
      throw new Error(res.msg || '提交订单失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error(error.message || '提交订单失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

onMounted(async () => {
  // 获取收货地址列表
  await getAddressList()
  
  // 判断是否是拍卖订单
  if (route.query.fromAuction && route.query.auctionId) {
    await getAuctionOrderData(route.query.auctionId)
  } else {
    // 从sessionStorage获取普通订单数据
    const orderDataStr = sessionStorage.getItem('orderData')
    if (orderDataStr) {
      try {
        const orderDataObj = JSON.parse(orderDataStr)
        if (orderDataObj && orderDataObj.items && Array.isArray(orderDataObj.items)) {
          orderData.value = {
            totalAmount: orderDataObj.totalAmount,
            items: orderDataObj.items.map(item => ({
              productId: item.productId,
              productName: item.productName,
              productPic: item.productPic,
              productPrice: item.productPrice,
              quantity: item.quantity,
              productAttr: item.productAttr
            }))
          }
        }
      } catch (error) {
        console.error('解析订单数据失败:', error)
        ElMessage.warning('订单数据格式错误')
      }
    }
  }
})
</script>

<style lang="scss" scoped>
.order-submit {
  padding: 40px;
  background: linear-gradient(135deg, #f6f8fb 0%, #f1f4f9 100%);
  min-height: 100vh;

  .box-card {
    max-width: 1200px;
    margin: 0 auto;
    border-radius: 24px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    border: none;
    overflow: hidden;

    :deep(.el-card__header) {
      padding: 24px 32px;
      border-bottom: 1px solid #eef0f5;
      background: linear-gradient(145deg, #ffffff, #f8f9fa);

      .card-header {
        display: flex;
        align-items: center;
        
        span {
          font-size: 24px;
          font-weight: 600;
          color: #2c3e50;
          position: relative;
          padding-left: 16px;
          
          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 24px;
            background: linear-gradient(45deg, #8B4513, #D2691E);
            border-radius: 2px;
          }
        }
      }
    }

    :deep(.el-card__body) {
      padding: 32px;
    }
  }

  .section-title {
    font-size: 20px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 24px;
    position: relative;
    padding-left: 16px;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 20px;
      background: linear-gradient(45deg, #8B4513, #D2691E);
      border-radius: 2px;
    }
  }

  .address-section {
    margin-bottom: 40px;

    .selected-address {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24px;
      background: linear-gradient(145deg, #ffffff, #f8f9fa);
      border-radius: 16px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }

      .address-info {
        .receiver {
          font-size: 18px;
          font-weight: 600;
          color: #2c3e50;
          margin-right: 16px;
        }

        .phone {
          font-size: 15px;
          color: #7f8c8d;
        }

        .address {
          margin-top: 12px;
          font-size: 15px;
          color: #7f8c8d;
          line-height: 1.6;
        }
      }

      :deep(.el-button) {
        padding: 12px 24px;
        font-size: 15px;
        border-radius: 12px;
        transition: all 0.3s ease;
        
        &:hover {
          color: #8B4513;
          background: rgba(139, 69, 19, 0.1);
        }
      }
    }

    .no-address {
      text-align: center;
      padding: 48px;
      background: linear-gradient(145deg, #ffffff, #f8f9fa);
      border-radius: 16px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);

      :deep(.el-button) {
        padding: 12px 32px;
        font-size: 16px;
        border-radius: 12px;
        background: linear-gradient(45deg, #8B4513, #D2691E);
        border: none;
        color: white;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(139, 69, 19, 0.25);
        }
      }
    }
  }

  .products-section {
    margin-bottom: 40px;

    .product-item {
      display: flex;
      align-items: center;
      padding: 24px;
      background: linear-gradient(145deg, #ffffff, #f8f9fa);
      border-radius: 16px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      margin-bottom: 16px;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }

      .product-img {
        width: 120px;
        height: 120px;
        border-radius: 12px;
        overflow: hidden;
        margin-right: 24px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
          
          &:hover {
            transform: scale(1.05);
          }
        }
      }

      .product-info {
        flex: 1;

        .product-name {
          font-size: 18px;
          font-weight: 600;
          color: #2c3e50;
          margin-bottom: 12px;
          line-height: 1.4;
        }

        .product-attr {
          font-size: 15px;
          color: #7f8c8d;
          margin-bottom: 16px;
          line-height: 1.6;
        }

        .product-price {
          display: flex;
          align-items: baseline;
          gap: 12px;

          .price {
            font-size: 24px;
            font-weight: 700;
            background: linear-gradient(45deg, #8B4513, #D2691E);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }

          .quantity {
            font-size: 16px;
            color: #7f8c8d;
          }
        }
      }
    }
  }

  .amount-section {
    margin-bottom: 40px;
    padding: 24px;
    background: linear-gradient(145deg, #ffffff, #f8f9fa);
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);

    .amount-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      font-size: 16px;
      color: #2c3e50;

      &.total {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #eef0f5;

        span {
          font-size: 18px;
          font-weight: 600;
        }

        .price {
          font-size: 28px;
          font-weight: 700;
          background: linear-gradient(45deg, #8B4513, #D2691E);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }

      .price {
        font-size: 18px;
        font-weight: 600;
        color: #8B4513;
      }
    }
  }

  .submit-section {
    text-align: right;

    :deep(.el-button) {
      padding: 16px 48px;
      font-size: 18px;
      font-weight: 600;
      border-radius: 12px;
      background: linear-gradient(45deg, #8B4513, #D2691E);
      border: none;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(139, 69, 19, 0.25);
      }
      
      &:active {
        transform: translateY(0);
      }
      
      &.is-disabled {
        background: #e8e8e8;
        color: #999;
        cursor: not-allowed;
        
        &:hover {
          transform: none;
          box-shadow: none;
        }
      }
    }
  }
}

:deep(.el-dialog) {
  border-radius: 24px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  
  .el-dialog__header {
    margin: 0;
    padding: 24px 32px;
    border-bottom: 1px solid #eef0f5;
    background: linear-gradient(145deg, #ffffff, #f8f9fa);
    
    .el-dialog__title {
      font-size: 20px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .el-dialog__body {
    padding: 32px;
  }
  
  .el-dialog__footer {
    padding: 24px 32px;
    border-top: 1px solid #eef0f5;
    background: linear-gradient(145deg, #ffffff, #f8f9fa);
  }
}

.address-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
  margin: -4px;

  .address-item {
    padding: 20px;
    background: linear-gradient(145deg, #ffffff, #f8f9fa);
    border-radius: 16px;
    margin-bottom: 16px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    }
    
    &.active {
      background: linear-gradient(145deg, #fff5e6, #fff8f0);
      border: 2px solid #8B4513;
    }

    .address-content {
      .receiver {
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;
        margin-right: 12px;
      }

      .phone {
        font-size: 15px;
        color: #7f8c8d;
      }

      .address {
        margin-top: 8px;
        font-size: 15px;
        color: #7f8c8d;
        line-height: 1.6;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  :deep(.el-button) {
    padding: 12px 24px;
    font-size: 15px;
    border-radius: 12px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
  
  :deep(.el-button--default) {
    border-color: #dcdfe6;
    
    &:hover {
      border-color: #8B4513;
      color: #8B4513;
    }
  }
  
  :deep(.el-button--primary) {
    background: linear-gradient(45deg, #8B4513, #D2691E);
    border: none;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(139, 69, 19, 0.25);
    }
  }
}

// 响应式布局优化
@media screen and (max-width: 768px) {
  .order-submit {
    padding: 20px;

    .box-card {
      :deep(.el-card__header) {
        padding: 20px;
        
        .card-header span {
          font-size: 20px;
        }
      }

      :deep(.el-card__body) {
        padding: 20px;
      }
    }

    .section-title {
      font-size: 18px;
    }

    .address-section {
      .selected-address {
        padding: 20px;
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;

        .address-info {
          width: 100%;
        }
      }
    }

    .products-section {
      .product-item {
        padding: 20px;
        flex-direction: column;
        align-items: flex-start;

        .product-img {
          width: 100%;
          height: 200px;
          margin-right: 0;
          margin-bottom: 16px;
        }

        .product-info {
          width: 100%;
        }
      }
    }

    .amount-section {
      padding: 20px;
    }

    .submit-section {
      :deep(.el-button) {
        width: 100%;
        padding: 12px 24px;
        font-size: 16px;
      }
    }
  }

  :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto;
    
    .el-dialog__body {
      padding: 20px;
    }
  }
}
</style>